<template>
  <div>
    <component :is="currentEditor" :content="content" ref="editor" @change="updateData"></component>
    <form method="post" enctype="multipart/form-data" style="display:none">
      <input :id="uuid" name="file" type="file" multiple ref="imageFile" @change="selectFile" accept="image/*">
    </form>
  </div>
</template>
<script>
import VueHtml5Editor from "vue-html5-editor";
import md5 from "js-md5";
import axios from "axios";
const axiosInstance = axios.create({});

export default {
  props: {
    value: String
  },
  created() {
    this.uuid = Math.random()
      .toString(36)
      .substring(3, 8);
  },
  mounted() {
    this.content = this.value;
  },
  data() {
    return {
      localUpload: false,
      content: "",
      option: {
        language: "zh-cn",
        visibleModules: [
          "text",
          "color",
          "font",
          "align",
          "list",
          "link",
          "unlink",
          "tabulation",
          // "image",
          "hr",
          "eraser",
          "undo",
          "upload-img",
          "full-screen"
        ],
        modules: [
          {
            name: "upload-img",
            icon: "fa fa-file-image-o",
            i18n: "time",
            show: true,
            init: function(editor) {},
            handler: editor => {
              this.$refs.imageFile.click();
            },
            destroyed: function(editor) {}
          }
        ]
      },
      isUploading: false
    };
  },
  computed: {
    currentEditor() {
      return new VueHtml5Editor(this.option);
    }
  },
  methods: {
    // 选择上传文件
    selectFile: async function(e) {
      var vm = this;
      if (e.target.files.length) {
        for (let i = 0; i < e.target.files.length; i++) {
          let currentFile = e.target.files[i];
          // 计算文件key
          let tmp = `${currentFile.lastModified +
            currentFile.size +
            Date.now()}`;
          let nameArr = currentFile.name.split(".");
          let extName = nameArr[nameArr.length - 1];
          let key = md5(tmp).substr(0, 10) + "_" + "." + extName;
          this.isUploading = true;
          let token = "";
          if (this.localUpload) {
            token = window.sessionStorage.getItem("token");
          } else {
            token = await this.getToken(key);
          }
          let imgUrl = await this.uploadQN(currentFile, token, key);
          // this.insertImage(imgUrl)
          this.$refs.editor.execCommand(
            "insertHTML",
            `<img src="${imgUrl}" />`
          );
          this.isUploading = false;
        }
      }
    },
    // 上传到七牛
    uploadQN(file, token, key) {
      var fd = new FormData();
      fd.append("token", token);
      fd.append("key", key);
      fd.append("file", file);

      return axiosInstance({
        method: "POST",
        url: "http://lywj-api.mrshare.cn/api/file/files/local/upload",
        data: fd,
        onUploadProgress: function(progressEvent) {
          var percentCompleted = Math.round(
            (progressEvent.loaded * 100) / progressEvent.total
          );
          console.log(percentCompleted);
        }
      })
        .then(function(res) {
          console.log("res", res);
          if (this.localUpload) {
            return `${window.api.imageDomain}${res.data.fileName}`;
          } else {
            return `${window.api.imageDomain}${res.data.key}`;
          }
        })
        .catch(function(err) {
          console.log("err", err);
        });
    },
    // 获取七牛上传token
    getToken(key) {
      return this.$store.dispatch("getUploadFileToken", key).then(ret => {
        return ret.body.token;
      });
    },
    updateData(content) {
      this.$emit("input", content);
    }
  },
  components: {}
};
</script>
<style>
</style>
